import Vue, { DirectiveOptions } from "vue";
import { message } from 'ant-design-vue';

// 事件防抖: 默认为点击事件
const debounce: DirectiveOptions = {
  bind: (el, binding) => {
    const { func = {} , immediate = true, envent = 'click' } = binding.value;
    func.$flag = immediate ? 1 : 0;
    func.$el = el;
    let timer: any, time = binding.arg ? Number(binding.arg) : 1000;
    let debounceHandle = function () {
      if (func.$flag === 1) {
        func.$fn = debounceHandle;
        func();
        func.$flag = 0;
        setTimeout(() => {
          func.$flag = 1;
        }, time)
      } else {
        // if (timer) {
          message.warning('请勿频繁操作！')
          // clearTimeout(timer);
        // }
        // timer = setTimeout(() => {
        //   func({ el, func: debounceHandle });
        // }, time)
      }
    }
    el.addEventListener(envent, debounceHandle)
  }
}

// 节流: 
const throttle: DirectiveOptions = {
  bind: (el: any, binding) => {
    const { func, immediate = true, envent = 'click' } = binding.value;
    el.$flag = immediate;
    let time = Number(binding.arg);
    el.addEventListener(envent, () => {
      if (el.$flag) {
        func();
        el.preTime = new Date().getTime();
        el.$flag = false;
      } else {
        const nowTime = new Date().getTime();
        if (!el.preTime || nowTime - el.preTime > el.time) {
          el.preTime = nowTime;
          func();
          el.$flag = true;
        }
      }
    })
  }
}

const draggable: DirectiveOptions = {
  inserted: function (el: any, binding) {
    el.style.cursor = 'move';
    el.onmousedown = function (e: any) {
      let disx = e.pageX - el.offsetLeft, disy = e.pageY - el.offsetTop, x: any = null, y: any = null;
      document.onmousemove = function (e) {
        document.onselectstart = function () { return false; };
        x = e.pageX - disx;
        y = e.pageY - disy;
        // let maxX = document.body.clientWidth - parseInt(window.getComputedStyle(el).width)
        // let maxY = document.body.clientHeight - parseInt(window.getComputedStyle(el).height)
        if (x < 0) {
          x = 0
        } 
        // else if (x > maxX) {
        //   x = maxX
        // }
        if (y < 0) {
          y = 0
        } 
        // else if (y > maxY) {
        //   y = maxY
        // }

        el.style.left = x + 'px'
        el.style.top = y + 'px'
        // console.log(maxY);
      }
      document.onmouseup = function (e) {
        if (x !== null && y !== null) {
          binding.value && binding.value({ x, y });
        }
        document.onmousemove = document.onmouseup = null
      }
    }
  },
}

export const directives = () => {
  Vue.directive("debounce", debounce);
  Vue.directive("throttle", throttle);
  Vue.directive("draggable", draggable);
};
